package cn.edu.gdu.quizpractice.controller.mini;

import cn.edu.gdu.quizpractice.dto.request.LoginRequest;
import cn.edu.gdu.quizpractice.entity.ApiResult;
import cn.edu.gdu.quizpractice.service.IUserService;
import cn.edu.gdu.quizpractice.entity.User;
import cn.edu.gdu.quizpractice.common.utils.JwtUtils;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.validation.annotation.Validated;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.ArrayList;
import java.util.List;

/**
 * @Author: Aubery
 * @Date: 2025-04-21-14:50
 * @Description:
 */
@RestController
@RequestMapping("/mini/user")
public class UserController {

    private static final Logger log = LoggerFactory.getLogger(UserController.class);

    @Autowired
    private IUserService userService;

    @Autowired
    private JwtUtils jwtUtils;

    /**
     * 微信小程序登录
     * @param request 包含微信小程序登录code和用户信息的请求体
     * @return 登录结果，包含JWT Token
     */
    @PostMapping("/login")
    public ApiResult<?> login(@Validated @RequestBody LoginRequest request) {
        try {
            log.info("接收到小程序登录请求: code={}", request.getCode() != null ? "***" : "null");
            User user = userService.login(request);

            if (user == null || user.getId() == null) {
                log.warn("微信登录处理失败，未返回有效的用户信息。");
                return ApiResult.fail("微信登录处理失败");
            }

            log.info("用户登录/注册成功: userId={}", user.getId());
            String token = jwtUtils.generateTokenByUserId(user.getId());
            log.info("为用户 ID {} 生成 Token 成功", user.getId());

            return ApiResult.success(token);

        } catch (RuntimeException e) {
            log.error("登录过程中发生运行时异常: {}", e.getMessage(), e);
            return ApiResult.fail("登录失败: " + e.getMessage());
        } catch (Exception e) {
            log.error("处理登录请求时发生未知错误: {}", e.getMessage(), e);
            return ApiResult.fail("登录处理异常");
        }
    }

}